package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author Administrator
 * @Description
 * 该任务负责与指定的客户端进行交互
 * @date 2022/5/12 16:34
 **/
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run(){
        try {

            String line = readline();
            String[] strings = line.split(" ");
            String method;
            String uri;
            String protoclo;
            method = strings[0];
            uri = strings[1];
            protoclo = strings[2];


            System.out.println( method);
            System.out.println(uri);
            System.out.println(protoclo);
            System.out.println(line);

            //解析消息头
            Map<String, String> headers = new HashMap<>();
            while (!(line = readline()).isEmpty()) {
                System.out.println(line);
                String[] split = line.split(": ");
                headers.put(split[0], split[1]);
            }
            System.out.println(headers);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String readline() throws IOException {

            InputStream inputStream = socket.getInputStream();
            StringBuilder sb = new StringBuilder();
            int d;
            char cur = 'a';
            char pre = 'a';
            while ((d = inputStream.read()) != -1) {
                cur = (char) d;
                if (pre == 13 && cur == 10) {
                    break;
                }
                sb.append(cur);
                pre = cur;
            }
            String line = sb.toString().trim();
            return line;

    }
}
